package com.beiing.tianshuai.tianshuai.message.ui;

import android.content.Context;
import android.content.Intent;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.beiing.tianshuai.tianshuai.R;
import com.beiing.tianshuai.tianshuai.base.BaseFragment;
import com.beiing.tianshuai.tianshuai.entity.ConversationListInfo;
import com.beiing.tianshuai.tianshuai.entity.ListUserBean;
import com.beiing.tianshuai.tianshuai.entity.UserInfoBean;
import com.beiing.tianshuai.tianshuai.mine.ui.LoginActivity;
import com.beiing.tianshuai.tianshuai.mine.view.MessageViewImpl;
import com.beiing.tianshuai.tianshuai.nim.main.fragment.SessionListFragment;
import com.beiing.tianshuai.tianshuai.rx.MsgEvent;
import com.beiing.tianshuai.tianshuai.rx.RxBus;
import com.beiing.tianshuai.tianshuai.util.DensityUtils;
import com.beiing.tianshuai.tianshuai.util.LogUtils;
import com.beiing.tianshuai.tianshuai.util.SPUtils;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.tianshuai.easypopup.EasyPopup;
import com.tianshuai.easypopup.HorizontalGravity;
import com.tianshuai.easypopup.VerticalGravity;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import cn.bingoogolapple.bgabanner.BGAOnNoDoubleClickListener;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by Jinni on 2017/7/6.
 * <p>
 * 消息界面
 */

public class MessageFragment extends BaseFragment implements MessageViewImpl {

    @BindView(R.id.toolbar)
    Toolbar mToolbar;
    @BindView(R.id.rl_helper)
    RelativeLayout mHelper;                             // 小率助手
    @BindView(R.id.rl_new_friend_message)
    RelativeLayout mNewFriendMessage;                   // 新朋友请求列表  ---->改动：跳转到消息提醒
    @BindView(R.id.action_search)
    ImageButton mFlSearchViewContainer;                 // 搜索框父布局
    @BindView(R.id.tv_message_num)
    TextView mTvIsHaveNewFriendRequest;                 // 新朋友提醒
    @BindView(R.id.tv_helper_message_num)
    TextView helperMessageNum;                          // 小率助手提醒
    @BindView(R.id.action_my_friends)
    ImageButton mBtnActionMyFriends;                    // 我的好友
    @BindView(R.id.action_menu)
    ImageButton mBtnActionMenu;                         // 菜单按钮
    @BindView(R.id.contact_fragment_container)
    FrameLayout mContactFragmentContainer;              // 会话列表

    private static final String TAG = "MessageFragment";

    private static Context mContext;

    private RxBus rxBus;

    /**
     * Toolbar上添加好友、我的群聊等弹出菜单
     */
    private EasyPopup mEasyPopup;

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_message;
    }

    @Override
    protected void init(View mView) {
        mContext = getActivity();
        mEasyPopup = new EasyPopup(mContext)
                .setContentView(R.layout.menu_message_fragment_toolbar)
                .setAnimationStyle(R.style.QQPopAnim)
                .setFocusAndOutsideEnable(true)
                .createPopup();

//        initStatusBar();
        initEasyPopup();
        initListener();
        initRxBus();

        FragmentTransaction fragmentTransaction = getChildFragmentManager().beginTransaction();
        fragmentTransaction.add(R.id.contact_fragment_container, new SessionListFragment());
        fragmentTransaction.commit();
    }

    /**
     * 初始化状态栏
     */
    private void initStatusBar() {
        int statusBarHeight = QMUIStatusBarHelper.getStatusbarHeight(mContext);
        mToolbar.setPadding(0, statusBarHeight, 0, 0);
    }

    private void isThereHaveNewFriendRequest() {
        int newFriendCount = (int) SPUtils.get(mContext, "newFriendCount", 0);
        if (newFriendCount > 0) {
            mTvIsHaveNewFriendRequest.setVisibility(View.VISIBLE);
            mTvIsHaveNewFriendRequest.setText("有新的好友请求");
        } else {
            mTvIsHaveNewFriendRequest.setVisibility(View.GONE);
        }
    }

    private void initEasyPopup() {
        TextView actionAddFriend = mEasyPopup.getView(R.id.action_add_friend);
        TextView actionCreateGroup = mEasyPopup.getView(R.id.action_create_group);
        TextView actionMyGroups = mEasyPopup.getView(R.id.action_my_group);
        actionAddFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                addFriend();
                mEasyPopup.dismiss();
            }
        });
        actionCreateGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createGroup();
                mEasyPopup.dismiss();
            }
        });
        actionMyGroups.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent toGroupsActivity = new Intent(getActivity(), MyGroupsActivity.class);
                startActivity(toGroupsActivity);
                mEasyPopup.dismiss();
            }
        });
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
    }
    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            QMUIStatusBarHelper.setStatusBarLightMode(getActivity());
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.i("onResume:", TAG);
        isThereHaveNewFriendRequest();
    }

    private void initListener() {

        // 通讯录点击事件
        mBtnActionMyFriends.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), MyFriendsActivity.class);
                intent.putExtra("uid", UserInfoBean.getUid(mContext));
                startActivity(intent);
            }
        });

        // 菜单按钮
        mBtnActionMenu.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int i = view.getLayoutParams().width / 2 - DensityUtils.dp2px(mContext, 2);
                mEasyPopup.showAtAnchorView(view, VerticalGravity.BELOW, HorizontalGravity.ALIGN_RIGHT, i, -DensityUtils.dp2px(mContext, 15));
            }
        });

        // 小率助手
        mHelper.setOnClickListener(new BGAOnNoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, HelperActivity.class);
                    startActivity(intent);
                } else {
                    toLogin();
                }
            }
        });

        // 搜索会话
        mFlSearchViewContainer.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, SearchContactActivity.class);
                    startActivity(intent);
                } else {
                    toLogin();
                }
            }
        });

        /*
         * 新朋友
         */
        mNewFriendMessage.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isLogin()) {
                    Intent intent = new Intent(mContext, NewFriendMessageActivity.class);
                    startActivity(intent);
                } else {
                    toLogin();
                }
            }
        });

//        // 系统通知
//        mSystemMessage.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                if (isLogin()) {
//                    Intent intent = new Intent(mContext, SystemMessageActivity.class);
//                    startActivity(intent);
//                } else {
//                    toLogin();
//                }
//            }
//        });
    }

    private void addFriend() {
        if (isLogin()) {
            Intent intent = new Intent(mContext, SearchFriendActivity.class);
            startActivity(intent);
        } else {
            toLogin();
        }
    }

    private boolean isLogin() {
        return !TextUtils.isEmpty(UserInfoBean.getUid(mContext));
    }

    private void toLogin() {
        Intent intent = new Intent(mContext, LoginActivity.class);
        startActivity(intent);
    }

    @Override
    public void showProgress() {

    }

    @Override
    public void hideProgress() {

    }

    @Override
    public void onRequestSuccess(ListUserBean bean) {
        ListUserBean.DataBean.IndexBean index = bean.getData().getIndex();
        if (index != null) {
            List<ListUserBean.DataBean.IndexBean.UserBean> users = index.getUser();
            if (users != null && users.size() > 0) {
                for (ListUserBean.DataBean.IndexBean.UserBean user : users) {
                    SPUtils.put(mContext, "avatar" + user.getUid(), user.getPhoto());
                    SPUtils.put(mContext, "nickname" + user.getUid(), user.getName());
                }
            }
            List<ListUserBean.DataBean.IndexBean.GroupBean> groups = index.getGroup();
            if (groups != null && groups.size() > 0) {
                for (ListUserBean.DataBean.IndexBean.GroupBean group : groups) {
                    SPUtils.put(mContext, "avatar" + group.getGroupid(), group.getGroupphoto());
                    SPUtils.put(mContext, "nickname" + group.getGroupid(), group.getGroupname());
                }
            }
        }
    }

    @Override
    public void onRequestFailed(Throwable throwable) {
        showShortText("网络异常");
    }

    /**
     * 创建群组
     */
    private void createGroup() {
        if (isLogin()) {
            Intent intent = new Intent(mContext, CreateGroupActivity.class);
            intent.putExtra("uid", UserInfoBean.getUid(mContext));
            startActivity(intent);
        }
    }

    private void initRxBus() {
        rxBus = RxBus.getInstanceBus();
        registerRxBus(MsgEvent.class, new Consumer<MsgEvent>() {
            @Override
            public void accept(MsgEvent msgEvent) throws Exception {
                if (TextUtils.equals(msgEvent.getType(), "messageNotice")) {
                    if ((Integer.parseInt(String.valueOf(msgEvent.getData())) > 0)) {
                        mTvIsHaveNewFriendRequest.setVisibility(View.VISIBLE);
                        mTvIsHaveNewFriendRequest.setText("有新的好友请求");
                    } else {
                        mTvIsHaveNewFriendRequest.setVisibility(View.GONE);
                    }
                }
            }
        });
    }

    public <T> void registerRxBus(Class<T> eventType, Consumer<T> action) {
        Disposable disposable = rxBus.doSubscribe(eventType, action, new Consumer<Throwable>() {
            @Override
            public void accept(@NonNull Throwable throwable) throws Exception {

            }
        });
        rxBus.addSubscription(this, disposable);
    }
}